#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @File   : tsSocketServerServ.py
# @Email  : xuexia_xu@feidee.com
# @Time   : 2024/4/7 13:56
# @Desc   : 《Python核心编程第3版》2.6 Twisted 时间戳 TCP 客户端

from twisted.internet import protocol, reactor

HOST = 'localhost'
PORT = 21567


class TSClntProtocol(protocol.Protocol):
    def sendData(self):
        data = input('>')
        if data:
            print('...sending %s...' % data)
            self.transport.write(data)
        else:
            self.transport.loseConnection()

    def connectionMade(self):
        self.sendData()

    def dataReceived(self, data: bytes):
        print(data)
        self.sendData()


class TSClntFactory(protocol.ClientFactory):
    protocol = TSClntProtocol
    clientConnectionLost = clientConnectionFailed = lambda self, connector, reason: reactor.stop()


reactor.connectTCP(HOST, PORT, TSClntFactory())
reactor.run()
